package com.lagou.controller;

import com.lagou.pojo.User;
import com.lagou.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Optional;

@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserRepository userRepository;

    @RequestMapping("toLogin")
    public String toLogin() {
        System.out.println("================++++++++++++++跳转登录页面");
        return "login";
    }

    @RequestMapping("loginSystem")
    public String loginSystem(String username, String password, HttpSession session) {
        // 合法用户，信息写入session，同时跳转到系统主页面
        User userParams = new User();
        userParams.setUsername(username);
        Example<User> example = Example.of(userParams);

        Optional<User> optional = userRepository.findOne(example);

        if(!optional.isPresent()){
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/login/toLogin";
        }

        User user = optional.get();


        if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
            System.out.println("合法用户");
            session.setAttribute("username", username + System.currentTimeMillis());
            return "redirect:/demo/result";
        } else {
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/login/toLogin";
        }
    }
}
